package com.yisen.dasan.controller;

import com.github.pagehelper.PageInfo;
import com.yisen.dasan.config.Auth;
import com.yisen.dasan.entity.FormResponse;
import com.yisen.dasan.pojo.Form;
import com.yisen.dasan.pojo.User;
import com.yisen.dasan.service.UserService;
import com.yisen.dasan.util.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @AuthorList: LiuYiSen
 * @Date: 2020/10/1 13:30
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @GetMapping("/hello")
    public ResultData hello(HttpServletRequest request){
        return new ResultData(true,200,"可以访问哦",null);
    }
    /**
     * 登录操作
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/login")
    public ResultData login(HttpServletRequest request,@RequestBody Map map){
        String token = userService.login(map.get("username").toString(), map.get("password").toString());
        if(token.equals("") || token.equals("账号或密码错误"))
            return new ResultData(false ,200,"用户名或密码错误！",null);
        else if(token.equals("邮件激活"))
            return new ResultData(false ,200,"请先通过邮件激活！",null);
        return new ResultData(true,200,"登陆成功",token);
    }

    /**
     * 注册操作
     * @param map
     * @return
     * @throws MessagingException
     */
    @PostMapping("/register")
    public ResultData register(@RequestBody Map map) throws MessagingException {
        boolean register = userService.register(map.get("username").toString(),
                map.get("password").toString(),
                map.get("email").toString());
        if(!register)
            return new ResultData(register ,200,"该用户名已存在",null);
        return new ResultData(register,200,"注册成功，请进入邮箱进行激活！",null);
    }

    /**
     * 激活用户操作
     * @param key
     * @return
     */
    @GetMapping("/affirm/{key}")
    public ResultData affirm(@PathVariable String key){
        boolean affirm = userService.affirm(key);
        if(affirm){
            return new ResultData(affirm ,200,"已成功激活该用户！请前往登陆！",null);
        }else{
            return new ResultData(affirm ,405,"此链接已失效！",null);
        }
    }

    /**
     * 显示该用户创建的所有表单
     * @param request
     * @return
     */
    @GetMapping("/selForm")
    @Auth
    public ResultData selForm(HttpServletRequest request,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum){
        PageInfo<FormResponse> forms = userService.selForm(pageNum,request);
        if(forms!=null){
            return new ResultData(true ,200,"查询成功！",forms);
        }else{
            return new ResultData(false ,405,"您还没有登陆请前往登陆！",null);
        }
    }
}

